﻿Imports System.IO
Imports System.Text.RegularExpressions
Imports Domino
Public Class StoreGroupControl

    Public Mainform As Form1
    Public SelectedGroupName As String
    Public SelectedGroupPath As String
    Dim SelectecRollOutName As String
    Dim MemberName As String = ""
    Dim MemberPath As String = ""
    Dim ThreadList As New ArrayList
#Region "Functions"
    'Groups
    Sub LoadGroups()
        Try
            WriteLogs("Refreshing Groups")
            DataGridGroup.Refresh()
            DataGridGroup.DataSource = Nothing
            Dim conn As New SqlClient.SqlConnection
            With conn
                .ConnectionString = My.Settings.DataSource
                .Open()
            End With

            Dim cmd As New SqlClient.SqlCommand
            With cmd
                .CommandText = "SELECT distinct [GroupName],[GroupPath] FROM [Management_Info_Sys].[dbo].[rollout_headers];"
                .CommandType = CommandType.Text
                .CommandTimeout = 60
                .Connection = conn
            End With
            Dim dt As New DataTable
            dt.Load(cmd.ExecuteReader)

            With DataGridGroup
                .AutoGenerateColumns = True
                .DataSource = dt
            End With

            For Each item As DataGridViewTextBoxColumn In DataGridGroup.Columns
                'MsgBox(item.HeaderText)
                item.AutoSizeMode = DataGridViewAutoSizeColumnMode.DisplayedCells

                If item.HeaderText = "GroupName" Then
                    item.HeaderText = "Group"
                ElseIf item.HeaderText = "GroupPath" Then
                    item.HeaderText = "Path"

                Else
                    item.Visible = False
                End If
            Next

            cmd.Dispose()
            cmd = Nothing
            conn.Dispose()
            conn = Nothing

        Catch ex As Exception
            WriteLogs(ex.Message)
            MsgBox(ex.Message)
        End Try
    End Sub
    Function AddGroup(GroupName As String, GroupPath As String) As Boolean
        Try
            WriteLogs("Connecting to server..")
            Dim connection As New Data.SqlClient.SqlConnection
            Dim command As New Data.SqlClient.SqlCommand
            connection.ConnectionString = My.Settings.DataSource

            command.CommandText = "INSERT INTO [dbo].[rollout_headers] ([GroupName],[GroupPath],[Column2])  " & _
                                                    "VALUES (@GroupName, @GroupPath, @Column2)"
            command.Parameters.Add("@GroupName", SqlDbType.NVarChar)
            command.Parameters.Add("@GroupPath", SqlDbType.NVarChar)
            command.Parameters.Add("@Column2", SqlDbType.NVarChar)

            connection.Open()
            command.Connection = connection

            command.Parameters("@GroupName").Value = GroupName
            command.Parameters("@GroupPath").Value = GroupPath
            command.Parameters("@Column2").Value = "Created, " & Now.ToString

            command.ExecuteNonQuery()

            command.Dispose()
            command = Nothing
            connection.Dispose()
            connection = Nothing
            WriteLogs("Group Successfully Added")
            Return True
        Catch ex As Exception
            WriteLogs(ex.Message)
            MsgBox(ex.Message, MsgBoxStyle.Critical)
            Return False
        End Try
    End Function
    Function EditGroup(OldGroupName As String, NewGroupName As String, OldGroupPath As String, NewGroupPath As String) As Boolean
        Try
            WriteLogs("Updating Group Information..")
            Dim connection As New Data.SqlClient.SqlConnection
            Dim command As New Data.SqlClient.SqlCommand
            connection.ConnectionString = My.Settings.DataSource

            command.CommandText = "UPDATE [dbo].[rollout_headers] " & _
                                  " SET [GroupName] = @newGroupName, [GroupPath] = @NewGroupPath, [Column2] = @Column2 " & _
                                  " WHERE [GroupName] = @oldGroupName"

            command.Parameters.Add("@newGroupName", SqlDbType.NVarChar)
            command.Parameters.Add("@NewGroupPath", SqlDbType.NVarChar)
            command.Parameters.Add("@Column2", SqlDbType.NVarChar)
            command.Parameters.Add("@oldGroupName", SqlDbType.NVarChar)

            connection.Open()
            command.Connection = connection

            command.Parameters("@newGroupName").Value = NewGroupName
            command.Parameters("@NewGroupPath").Value = NewGroupPath
            command.Parameters("@Column2").Value = "Edited, " & Now.ToString
            command.Parameters("@oldGroupName").Value = OldGroupName

            command.ExecuteNonQuery()

            command.Dispose()
            command = Nothing
            connection.Dispose()
            connection = Nothing
            WriteLogs("Group Successfully Updated")
            Return True
        Catch ex As Exception
            WriteLogs(ex.Message)
            MsgBox(ex.Message, MsgBoxStyle.Critical)
            Return False
        End Try
    End Function
    Sub DeleteGroup(GroupName As String)
        Try
            WriteLogs("Connecting to Server..")
            Dim connection As New Data.SqlClient.SqlConnection
            Dim command As New Data.SqlClient.SqlCommand
            connection.ConnectionString = My.Settings.DataSource
            command.CommandText = "DELETE from [dbo].[rollout_headers] " & _
                                                    "WHERE [GroupName] = @GroupName;"
            command.Parameters.Add("@GroupName", SqlDbType.NVarChar)
            connection.Open()
            command.Connection = connection

            command.Parameters("@GroupName").Value = GroupName

            command.ExecuteNonQuery()
            command.Dispose()
            command = Nothing
            connection.Dispose()
            connection = Nothing
            WriteLogs("Group Successfully Deleted")
        Catch ex As Exception
            WriteLogs(ex.Message)
            MsgBox(ex.Message)
        End Try
    End Sub
    'Members
    Sub LoadMembers(Groupname As String)
        Try
            Freeze()
            WriteLogs("Refreshing Members of " & Groupname)
            DataGridMembers.DataSource = Nothing
            DataGridMembers.Refresh()
            Dim conn As New SqlClient.SqlConnection
            With conn
                .ConnectionString = My.Settings.DataSource
                .Open()
            End With

            Dim cmd As New SqlClient.SqlCommand

            With cmd
                If Groupname = Nothing Then
                    .CommandText = "SELECT [MemberName],[MemberSharedPath],[LastSuccessRollout],[TimeStamp],[Status_] FROM [Management_Info_Sys].[dbo].[rollout_headers] where MemberName <> ''"
                Else
                    .CommandText = "SELECT [MemberName],[MemberSharedPath],[LastSuccessRollout],[TimeStamp],[Status_] FROM [Management_Info_Sys].[dbo].[rollout_headers] where [GroupName]= '" & Groupname & "' and MemberName <> ''"
                End If
                'If FilterStatus <> "" Then
                '    .CommandText = .CommandText & " and [Status_]='" & FilterStatus & "'"
                'End If
                If cmbSHow.SelectedItem = "All" Then
                ElseIf cmbSHow.SelectedItem = "Success" Then
                    .CommandText = .CommandText & " and [Status_]='Success'"
                ElseIf cmbSHow.SelectedItem = "Failed" Then
                    .CommandText = .CommandText & " and [Status_]='Failed'"
                ElseIf cmbSHow.SelectedItem = "Null" Then
                    .CommandText = .CommandText & " and [Status_] is null"
                ElseIf cmbSHow.SelectedItem = "Cancelled" Then
                    .CommandText = .CommandText & " and [Status_]='Failed'"
                End If
                .CommandType = CommandType.Text
                .CommandTimeout = 60
                .Connection = conn
            End With
            Dim dt As New DataTable
            dt.Load(cmd.ExecuteReader)

            With DataGridMembers
                .AutoGenerateColumns = True
                .DataSource = dt
            End With

            For Each item As DataGridViewTextBoxColumn In DataGridMembers.Columns
                'MsgBox(item.HeaderText)
                item.AutoSizeMode = DataGridViewAutoSizeColumnMode.Fill

                If item.HeaderText = "MemberName" Then
                    item.HeaderText = "Member Name"
                ElseIf item.HeaderText = "MemberSharedPath" Then
                    item.HeaderText = "Member Shared Path"
                ElseIf item.HeaderText = "LastSuccessRollout" Then
                    item.HeaderText = "Last Rollout"
                ElseIf item.HeaderText = "TimeStamp" Then
                    item.HeaderText = "Time Stamp"
                ElseIf item.HeaderText = "Status_" Then
                    item.HeaderText = "Status"
                Else
                    item.Visible = False
                End If
            Next

            cmd.Dispose()
            cmd = Nothing
            conn.Dispose()
            conn = Nothing

            'Dim StatusColumn As New DataGridViewTextBoxColumn
            'With StatusColumn
            '    .HeaderText = "Status"
            '    .Name = "Status_"
            '    .AutoSizeMode = DataGridViewAutoSizeColumnMode.Fill
            'End With

            'DataGridMembers.Columns.Insert(DataGridMembers.ColumnCount, StatusColumn)
        Catch ex As Exception
            WriteLogs(ex.Message)
            MsgBox(ex.Message)
        End Try
        DeFreeze()
    End Sub
    Function AddMember(Groupname As String, GroupPath As String, Membername As String, MemberPath As String, MemberID As String) As Boolean
        Try
            WriteLogs("Connecting to Server")
            Dim connection As New Data.SqlClient.SqlConnection
            Dim command As New Data.SqlClient.SqlCommand
            connection.ConnectionString = My.Settings.DataSource

            command.CommandText = "INSERT INTO [dbo].[rollout_headers] ([GroupName],[GroupPath],[MemberName],[MemberSharedPath],[TimeStamp],[Column1],[Column2])  " & _
                                                    "VALUES (@GroupName, @GroupPath,@MemberName,@MemberSharedPath,@TimeStamp,@Column1, @Column2)"
            command.Parameters.Add("@GroupName", SqlDbType.NVarChar)
            command.Parameters.Add("@GroupPath", SqlDbType.NVarChar)
            command.Parameters.Add("@MemberName", SqlDbType.NVarChar)
            command.Parameters.Add("@MemberSharedPath", SqlDbType.NVarChar)
            command.Parameters.Add("@TimeStamp", SqlDbType.NVarChar)
            command.Parameters.Add("@Column1", SqlDbType.NVarChar)
            command.Parameters.Add("@Column2", SqlDbType.NVarChar)

            connection.Open()
            command.Connection = connection

            command.Parameters("@GroupName").Value = Groupname
            command.Parameters("@GroupPath").Value = GroupPath
            command.Parameters("@MemberName").Value = Membername
            command.Parameters("@MemberSharedPath").Value = MemberPath
            command.Parameters("@TimeStamp").Value = Now.ToString
            command.Parameters("@Column1").Value = MemberID
            command.Parameters("@Column2").Value = "Created, " & Now.ToString

            command.ExecuteNonQuery()

            command.Dispose()
            command = Nothing
            connection.Dispose()
            connection = Nothing
            WriteLogs("Member Successfully Added")
            Return True
        Catch ex As Exception
            WriteLogs(ex.Message)
            MsgBox(ex.Message, MsgBoxStyle.Critical)
            Return False
        End Try
        Return False
    End Function
    Function DeleteMember(MemberName As String, GroupName As String) As Boolean
        Try
            WriteLogs("Connecting to Server..")
            Dim connection As New Data.SqlClient.SqlConnection
            Dim command As New Data.SqlClient.SqlCommand
            connection.ConnectionString = My.Settings.DataSource

            command.CommandText = "DELETE FROM [dbo].[rollout_headers] " & _
                                                    "WHERE [MemberName] = @MemberName and [GroupName] = @GroupName;"
            command.Parameters.Add("@GroupName", SqlDbType.NVarChar)
            command.Parameters.Add("@MemberName", SqlDbType.NVarChar)

            connection.Open()
            command.Connection = connection

            command.Parameters("@GroupName").Value = GroupName
            command.Parameters("@MemberName").Value = MemberName

            command.ExecuteNonQuery()

            command.Dispose()
            command = Nothing
            connection.Dispose()
            connection = Nothing
            WriteLogs("Member Successfully Deleted")
            Return True
        Catch ex As Exception
            WriteLogs(ex.Message)
            MsgBox(ex.Message)
        End Try
        Return False
    End Function
    Sub DeleteRollOut()
        Freeze()
        Try
            Dim SelectedRollOutFile As New FileInfo(SelectedGroupPath & SelectecRollOutName)
            For Each rows As DataGridViewRow In DataGridMembers.Rows
                Dim CurrentMemberName As String = rows.Cells("MemberName").Value
                Dim CurrentMemberPath As String = rows.Cells("MemberSharedPath").Value
                If (CurrentMemberName <> "" And CurrentMemberPath <> "") Then
                    WriteTable(rows.Index, "Deleting.." & SelectecRollOutName, DataGridMembers)
                    WriteLogs("Deleting.." & SelectecRollOutName & " to " & CurrentMemberName)
                    If File.Exists(CurrentMemberPath & SelectedRollOutFile.Name) Then
                        File.Delete(CurrentMemberPath & SelectedRollOutFile.Name)
                        UpdateLastRollout(CurrentMemberName, SelectedGroupName, SelectedRollOutFile.Name.ToString, "Cancelled")
                        WriteLogs(SelectedRollOutFile.Name & " Deleted from " & CurrentMemberName)
                        WriteTable(rows.Index, "Cancelled " & SelectecRollOutName, DataGridMembers)
                    Else
                        WriteTable(rows.Index, "", DataGridMembers)
                    End If

                End If

            Next
            File.Delete(SelectedRollOutFile.FullName)
        Catch ex As Exception
            WriteLogs(ex.Message)
        End Try
        DeFreeze()
    End Sub
    Function UpdateLastRollout(MemberName As String, GroupName As String, LastRollOutname As String, Status As String) As Boolean
        WriteLogs("Connecting to Server..")
        Try
            Dim connection As New Data.SqlClient.SqlConnection
            Dim command As New Data.SqlClient.SqlCommand
            connection.ConnectionString = My.Settings.DataSource

            command.CommandText = "UPDATE [dbo].[rollout_headers]" & _
                                " SET [LastSuccessRollout]=@LastSuccessRollout, [TimeStamp]=@TimeStamp,[Status_]=@Status" & _
                                " WHERE [MemberName] = @MemberName and [GroupName] = @GroupName;"

            command.Parameters.Add("@LastSuccessRollout", SqlDbType.NVarChar)
            command.Parameters.Add("@TimeStamp", SqlDbType.NVarChar)
            command.Parameters.Add("@Status", SqlDbType.NVarChar)
            command.Parameters.Add("@GroupName", SqlDbType.NVarChar)
            command.Parameters.Add("@MemberName", SqlDbType.NVarChar)

            connection.Open()
            command.Connection = connection

            command.Parameters("@LastSuccessRollout").Value = LastRollOutname
            command.Parameters("@TimeStamp").Value = Now.ToString
            command.Parameters("@Status").Value = Status
            command.Parameters("@GroupName").Value = GroupName
            command.Parameters("@MemberName").Value = MemberName

            command.ExecuteNonQuery()

            command.Dispose()
            command = Nothing
            connection.Dispose()
            connection = Nothing
            WriteLogs("Member's Last Rollout Updated")
            Return True
        Catch ex As Exception
            WriteLogs(ex.Message)
        End Try
        Return False
    End Function
    'Send Roll Out
    Sub SendRollOut()
        Freeze()
        Try
            Dim SelectedRollOutFile As New FileInfo(SelectedGroupPath & SelectecRollOutName)
            'Sending 

            For Each rows As DataGridViewRow In DataGridMembers.Rows
                If rows.Visible = False Then
                    GoTo GetNext
                End If
                Dim CurrentMemberName As String = rows.Cells("MemberName").Value
                Dim CurrentMemberPath As String = rows.Cells("MemberSharedPath").Value
                If (CurrentMemberName <> "" And CurrentMemberPath <> "") Then
                    WriteTable(rows.Index, "Sending.." & SelectecRollOutName, DataGridMembers)
                    WriteLogs("Sending.." & SelectecRollOutName & " to " & CurrentMemberName)
                    If File.Exists(CurrentMemberPath & SelectedRollOutFile.Name) Then
                        WriteTable(rows.Index, "Already Exist", DataGridMembers)
                        GoTo GoNextWithRetun
                        'File.Delete(CurrentMemberPath & SelectedRollOutFile.Name)
                    End If
                    If NetworkWithProgress(CurrentMemberPath & SelectedRollOutFile.Name, SelectedRollOutFile.FullName) = True Then

                        WriteTable(rows.Index, "Success", DataGridMembers)
                        'Update Last Rollout
GoNextWithRetun:
                        'GoTo Email
                        UpdateLastRollout(CurrentMemberName, SelectedGroupName, SelectedRollOutFile.Name.ToString, "Success")
                        rows.Cells("LastSuccessRollout").Value = SelectedRollOutFile.Name.ToString
                        rows.Cells("TimeStamp").Value = Now.ToString
                        rows.Cells("Status_").Value = "Success"
                        WriteLogs("Done sending to " & CurrentMemberName)
                    Else
Email:
                        'Email
                        'Get Store Email
                        Dim Email As String = GetStoreEmail(CurrentMemberName)
                        If SendEmail("ROLLOUT : " & SelectedRollOutFile.Name, "ROLLOUT.txt", SelectedRollOutFile.FullName, Email, "") Then
                            WriteTable(rows.Index, "Success, Email", DataGridMembers)
                            UpdateLastRollout(CurrentMemberName, SelectedGroupName, SelectedRollOutFile.Name.ToString, "Success, Email")
                            rows.Cells("LastSuccessRollout").Value = SelectedRollOutFile.Name.ToString
                            rows.Cells("TimeStamp").Value = Now.ToString
                            rows.Cells("Status_").Value = "Success, Email"
                            WriteLogs("Done sending to " & CurrentMemberName & " through email")
                        Else
                            GoTo FinalFail
                        End If
FinalFail:
                        UpdateLastRollout(CurrentMemberName, SelectedGroupName, SelectedRollOutFile.Name.ToString, "Failed")
                        rows.Cells("Status_").Value = "Failed to send to " & CurrentMemberName
                        WriteTable(rows.Index, "Failed", DataGridMembers)
                        WriteLogs("Failed to send to " & CurrentMemberName)
                    End If
                End If
GetNext:
            Next
        Catch ex As Exception
            WriteLogs(ex.Message)
        End Try
        DeFreeze()
    End Sub
    Function GetStoreEmail(MatchString As String) As String
        Dim splitString As String()
        splitString = MatchString.Split("_")
        Dim Company As String = splitString(0)
        Dim Storename As String = splitString(1)

        Dim conn As New SqlClient.SqlConnection
        With conn
            .ConnectionString = My.Settings.DataSource
            .Open()
        End With

        Dim cmd As New SqlClient.SqlCommand
        With cmd
            .CommandText = "SELECT [email] FROM [dbo].[stores] where [company]=@company and [storename] = @storename"
            .CommandType = CommandType.Text
            .CommandTimeout = 60

            .Parameters.Add("@company", SqlDbType.NVarChar)
            .Parameters.Add("@storename", SqlDbType.NVarChar)

            .Connection = conn

            .Parameters("@company").Value = Company
            .Parameters("@storename").Value = Storename
        End With


        Dim dt As New DataTable
        dt.Load(cmd.ExecuteReader)

        Dim Email As String = "Not Found"
        For Each item As DataRow In dt.Rows
            Email = item("email").ToString
            Return Email
        Next
        Return Email
    End Function

    Function SendEmail(Title As String, BodyFile As String, AttachmentFile As String, Recipient As String, CC As String) As Boolean
        Try
            Dim ns As New NotesSession
            Dim db As NotesDatabase
            Dim doc As NotesDocument
            If Not (ns Is Nothing) Then
                WriteLogs("Initializing Mail..")
                ns.Initialize(My.Settings.DominoPassword)
                WriteLogs("Opening Mail..")
                db = ns.GetDatabase(My.Settings.DominoServer, My.Settings.DominoAccountFile, False)
                If db.IsOpen = True Then
                    'Already open for mail
                Else
                    db.OPENMAIL()
                End If
                If Not (db Is Nothing) Then
                    WriteLogs("Creating Document..")
                    doc = db.CreateDocument()
                    doc.ReplaceItemValue("Form", "Memo")
                    doc.ReplaceItemValue("SendTo", Recipient)
                    'doc.ReplaceItemValue("CopyTo", CC)
                    doc.ReplaceItemValue("Subject", Title)
                    doc.SaveMessageOnSend = My.Settings.DominoSaveOnSend

                    'Load Document
                    WriteLogs("Loading Document..")
                    'Dim rftFile As New RichTextBox
                    'rftFile.LoadFile(BodyFile)

                    Dim BodyMsg As String = ""
                    If File.Exists("rollout.txt") Then
                        Using sr As New StreamReader("rollout.txt")
                            BodyMsg = sr.ReadToEnd()
                        End Using
                    Else
                        WriteLogs("rollout.txt not found!")
                    End If

                    Dim rt As NotesRichTextItem
                    rt = doc.CreateRichTextItem("Body")

                    If AttachmentFile <> "" Then
                        WriteLogs("Attaching File..")
                        Dim fileinfo_ As New FileInfo(AttachmentFile)
                        Call rt.EmbedObject(EMBED_TYPE.EMBED_ATTACHMENT, "", fileinfo_.FullName, fileinfo_.Name)
                        rt.AppendText("===============================================================")
                        Call rt.AddNewLine(3)
                    End If

                    rt.AppendText(BodyMsg)
                    rt.AddNewLine(1)


                    WriteLogs("Sending..")
                    doc.Send(False)
                    rt = Nothing
                    doc = Nothing
                    db = Nothing
                    ns = Nothing
                    WriteLogs("Message Sent to " & Recipient)
                    Return True
                End If
                db = Nothing
                ns = Nothing
            Else
                WriteLogs("Error Domino Database Returns Nothing")
            End If
        Catch ex As Exception
            WriteLogs("Error " + ex.Message.ToString())
            'MsgBox("Error: " + ex.ToString())
        End Try
        'WriteLogs("Error Domino Returns Unkown")
        Return False
    End Function
    'Open Folder
    Sub OpenSharedFolder(Directory As String)
        Try
            Dim loc As String
            loc = "explorer.exe " & Directory
            WriteLogs("Exploring.. " & Directory)
            Shell(loc, AppWinStyle.NormalFocus)
            WriteLogs("Done Exploring " & Directory)
        Catch ex As Exception
            WriteLogs(ex.Message)
        End Try
    End Sub
    'Copy File
    Public Function ReadBinaryFile(strFilename As String) As Byte()
        Dim position As Integer = 0
        Dim bufferSize As Integer = 4096
        Dim bytes() As Byte
        Mainform.ToolStripProgressBar1.ProgressBar.Value = 0

        Using fsOpen As FileStream = New FileStream(strFilename, FileMode.Open)
            ReDim bytes((fsOpen.Length) - 1)
            Do
                If (position + bufferSize) > fsOpen.Length Then
                    fsOpen.Read(bytes, position, fsOpen.Length - position)
                    Exit Do
                Else
                    fsOpen.Read(bytes, position, bufferSize)
                End If
                ProgressStatus(((position / fsOpen.Length) * 100), "Analyzing ")
                Application.DoEvents()
                position += bufferSize
            Loop
        End Using

        Return bytes

    End Function
    Public Sub SaveBinaryFile(strFilename As String, bytesToWrite() As Byte)
        Dim position As Integer = 0
        Dim BufferSize As Integer = 4096
        Mainform.ToolStripProgressBar1.ProgressBar.Value = 0

        Using fsNew As FileStream = New FileStream(strFilename, FileMode.Create, FileAccess.Write)
            Do
                Dim intToCopy As Integer = Math.Min(BufferSize, bytesToWrite.Length - position)
                Dim buffer(intToCopy - 1) As Byte
                Array.Copy(bytesToWrite, position, buffer, 0, intToCopy)
                fsNew.Write(buffer, 0, buffer.Length)
                ProgressStatus(((position / bytesToWrite.Length) * 100), "Sending ")
                Application.DoEvents()
                position += intToCopy
            Loop While position < bytesToWrite.Length
        End Using
    End Sub
    Function NetworkWithProgress(OutputFile As String, InputFile As String) As Boolean
        Try
            If File.Exists(OutputFile) = False Then
Writing:
                SyncLock Me
                    SaveBinaryFile(OutputFile, ReadBinaryFile(InputFile))
                End SyncLock
            Else
                WriteStatus(OutputFile & "Already Exist")
                WriteLogs(OutputFile & "Already Exist")
                Try
                    Dim a = MsgBox("File already exist!, Do you want to overwrite?", vbYesNo)
                    If a = MsgBoxResult.Yes Then
                        File.Delete(OutputFile)
                        GoTo Writing
                    End If
                Catch ex As Exception
                End Try
                Return True
            End If
        Catch ex As Exception
            WriteStatus(ex.Message)
            WriteLogs(ex.Message)
        End Try

        If File.Exists(OutputFile) Then
            Return True
        End If
        Return False
    End Function

    Sub VerifyInstallation()
        For Each rows As DataGridViewRow In DataGridMembers.Rows
            Dim CurrentMemberName As String = rows.Cells("MemberName").Value
            Dim CurrentMemberPath As String = rows.Cells("MemberSharedPath").Value
            Dim Split1 As String() = Regex.Split(CurrentMemberPath, "\\", RegexOptions.None)
            Dim Ip As String = Split1(2)

            If ping(Ip) = True Then
                WriteTable(rows.Index, "Connected", DataGridMembers)
                WriteLogs(CurrentMemberName & " Connected")
                If Directory.Exists(CurrentMemberPath) Then
                    WriteTable(rows.Index, "Directory Found", DataGridMembers)
                    WriteLogs(CurrentMemberName & " Directory Found")
                    If File.Exists(CurrentMemberPath & "AutoRollOut.exe") Then
                        WriteTable(rows.Index, "Verified", DataGridMembers)
                        WriteLogs(CurrentMemberName & " Installation Verified")
                    Else
                        WriteTable(rows.Index, "Installation Not Found", DataGridMembers)
                        WriteLogs(CurrentMemberName & " Installation Not Found")
                    End If
                Else
                    WriteTable(rows.Index, "Directory Not Found", DataGridMembers)
                    WriteLogs(CurrentMemberName & " Directory Not Found")
                End If
            Else
                WriteTable(rows.Index, "Not Connected", DataGridMembers)
                WriteLogs(CurrentMemberName & " Not Connected")
            End If
        Next
        DeFreeze()
    End Sub
    Private Sub UpdatedAllAutoRollOut(UpdateFile As String)
        Try
            For Each rows As DataGridViewRow In DataGridMembers.Rows
                Dim CurrentMemberName As String = rows.Cells("MemberName").Value
                Dim CurrentMemberPath As String = rows.Cells("MemberSharedPath").Value
                WriteLogs("Initializing...")
                WriteTable(rows.Index, "Initializing..", DataGridMembers)
                If File.Exists(CurrentMemberPath & "AutoRollOut.exe") Then
                    File.Delete(CurrentMemberPath & "AutoRollOut.exe")
                    WriteTable(rows.Index, "Copying Update..", DataGridMembers)
                    WriteLogs("Copying Update..")
                    'If NetworkWithProgress(CurrentMemberPath & "AutoRollOut.exe", UpdateFile) = True Then
                    '    WriteTable(rows.Index, "Store Client Updated", DataGridMembers)
                    '    WriteLogs("Store client has been updated.")
                    'Else
                    '    WriteLogs("Store client updating failed")
                    'End If

                    File.Copy(UpdateFile, CurrentMemberPath & "AutoRollOut.exe")
                    If File.Exists(CurrentMemberPath & "AutoRollOut.exe") = True Then
                        WriteTable(rows.Index, "Store Client Updated", DataGridMembers)
                        WriteLogs("Store client has been updated.")
                    Else
                        WriteLogs("Store client updating failed")
                    End If
                Else
                    WriteLogs("File or Folder does not exist")
                End If
            Next
        Catch ex As Exception
            WriteLogs(ex.Message)
        End Try
        DeFreeze()
    End Sub
    Function ping(ip As String) As Boolean
        Try
            Dim dom As String = ip

            If InStr(dom, ":") Then
                Dim spliter As String()
                spliter = Split(dom, ":")
                dom = spliter(0)
            End If
            Dim yPing As New Net.NetworkInformation.Ping
            Dim yPingReply As Net.NetworkInformation.PingReply
            yPingReply = yPing.Send(dom)
            Dim return_ As String = yPingReply.Status.ToString

            If return_ = "Success" Then
                Return True
            Else
                Return False
            End If
        Catch ex As Exception
            Return False
        End Try
    End Function

    'Working State
    Public Sub Freeze()
        Try
            Mainform.Freeze()
            DataGridGroup.Enabled = False
            DataGridMembers.Enabled = False
            btnAbort.Visible = True
            cmbSHow.Enabled = False
        Catch ex As Exception

        End Try
    End Sub
    Public Sub DeFreeze()
        Try
            Mainform.DeFreeze()
            DataGridGroup.Enabled = True
            DataGridMembers.Enabled = True
            btnAbort.Visible = False
            Mainform.ToolStripProgressBar1.Value = 0
            ThreadList.Clear()
            cmbSHow.Enabled = True
        Catch ex As Exception

        End Try
    End Sub

#End Region
#Region "Logs"
    Sub WriteTable(index As Integer, Message As String, DataGridView1 As DataGridView)
        Try
            DataGridView1.Rows(index).Cells("Status_").Value = Message
            WriteLogs(Message)
        Catch ex As Exception

        End Try
    End Sub
    Sub WriteLogs(Message As String)
        Try
            txtlogs.AppendText(Now & " : " & Message & vbCrLf)
            Mainform.ToolStripStatusLabel1.Text = Message
            SaveLogs(Now & " : " & Message)
        Catch ex As Exception

        End Try
    End Sub
    Sub SaveLogs(MessageLine)
        Try
            Dim FILE_NAME As String = My.Application.Info.DirectoryPath & "\logs.txt"
            Dim objWriter As New System.IO.StreamWriter(FILE_NAME, True)
            'For Each line In TextBox1.Lines
            '    objWriter.WriteLine(line)
            'Next
            objWriter.WriteLine(MessageLine)
            objWriter.Close()
            'WriteStatus("Done")
        Catch ex As Exception
            WriteStatus(ex.Message)
        End Try
    End Sub
    Sub WriteStatus(Message As String)
        Mainform.ToolStripStatusLabel1.Text = Message
    End Sub
    Sub ProgressStatus(val As Integer, Optional ByVal Msg As String = "")
        Try

            Mainform.ToolStripProgressBar1.ProgressBar.Value = val
            Mainform.ToolStripProgressBar1.ProgressBar.Refresh()
            If val <> 0 Then
                WriteLogs(Msg & " " & val & "%")
            End If
        Catch ex As Exception

        End Try
    End Sub
#End Region
    Private Sub StoreGroupControl_Load(sender As Object, e As EventArgs) Handles MyBase.Load
        CheckForIllegalCrossThreadCalls = False
        cmbSHow.SelectedIndex = 0
        'MsgBox(cmbSHow.SelectedIndex =)
        LoadGroups()
        For Each selecteditems As DataGridViewRow In DataGridGroup.SelectedRows
            LoadMembers(selecteditems.Cells("GroupName").Value)
            Exit For
        Next
    End Sub
    Private Sub DataGridGroup_CellContentClick(sender As Object, e As DataGridViewCellEventArgs) Handles DataGridGroup.CellContentClick
        SelectedGroupName = DataGridGroup.Rows(e.RowIndex).Cells("GroupName").Value
        SelectedGroupPath = DataGridGroup.Rows(e.RowIndex).Cells("GroupPath").Value
        LoadMembers(SelectedGroupName)
    End Sub

    Private Sub AddMemberToolStripMenuItem_Click(sender As Object, e As EventArgs)

    End Sub


    Private Sub DeleteToolStripMenuItem_Click(sender As Object, e As EventArgs) Handles DeleteToolStripMenuItem.Click
        DataGridMembers.Refresh()

        If MemberName = "" Or SelectedGroupName = "" Then
            Return
        End If

        If MsgBox("Are you sure you want to Delete " & MemberName & " from " & SelectedGroupName & " Group?", vbYesNo) = MsgBoxResult.Yes Then
            If DeleteMember(MemberName, SelectedGroupName) = True Then
                MsgBox("Member Deleted!", vbInformation)
                Try
                    For Each selecteditems As DataGridViewRow In DataGridGroup.SelectedRows
                        LoadMembers(SelectedGroupName)
                        Exit For
                    Next
                Catch ex As Exception

                End Try
            End If
        End If
    End Sub
    Private Sub CreateRolloutToolStripMenuItem_Click(sender As Object, e As EventArgs)

    End Sub
    Private Sub DataGridGroup_SelectionChanged(sender As Object, e As EventArgs) Handles DataGridGroup.SelectionChanged
        For Each selecteditems As DataGridViewRow In DataGridGroup.SelectedRows
            SelectedGroupName = selecteditems.Cells("GroupName").Value
            SelectedGroupPath = selecteditems.Cells("GroupPath").Value
            LoadMembers(SelectedGroupName)
            Exit For
        Next

    End Sub

    Private Sub Button1_Click(sender As Object, e As EventArgs) Handles btnAbort.Click
        Try
            For Each item As Threading.Thread In ThreadList
                item.Abort()
            Next

            DeFreeze()
        Catch ex As Exception

        End Try
    End Sub
    Private Sub DataGridMembers_SelectionChanged(sender As Object, e As EventArgs) Handles DataGridMembers.SelectionChanged
        For Each selecteditems As DataGridViewRow In DataGridMembers.SelectedRows
            MemberName = selecteditems.Cells("MemberName").Value
            MemberPath = selecteditems.Cells("MemberSharedPath").Value
            Exit For
        Next
    End Sub

    Private Sub DataGridView1_CellContentClick(sender As Object, e As DataGridViewCellEventArgs) Handles DataGridMembers.CellContentClick
        Try
            MemberName = DataGridMembers.Rows(e.RowIndex).Cells("MemberName").Value
            MemberPath = DataGridMembers.Rows(e.RowIndex).Cells("MemberSharedPath").Value
        Catch ex As Exception

        End Try
    End Sub
    Private Sub ExploreToolStripMenuItem_Click(sender As Object, e As EventArgs) Handles ExploreToolStripMenuItem.Click
        Dim t As New Threading.Thread(AddressOf OpenSharedFolder)
        t.Start(MemberPath)
        'OpenSharedFolder(MemberPath)
    End Sub

    Private Sub DeleteGroupToolStripMenuItem_Click(sender As Object, e As EventArgs)

    End Sub


    Private Sub RefreshToolStripMenuItem_Click(sender As Object, e As EventArgs) Handles RefreshToolStripMenuItem.Click
        LoadGroups()
        For Each selecteditems As DataGridViewRow In DataGridGroup.SelectedRows
            LoadMembers(selecteditems.Cells("GroupName").Value)
            Exit For
        Next
    End Sub

    Private Sub CheckBox1_CheckedChanged(sender As Object, e As EventArgs)
        LoadMembers(SelectedGroupName)
    End Sub

    Private Sub cmbSHow_SelectedIndexChanged(sender As Object, e As EventArgs) Handles cmbSHow.SelectedIndexChanged
        LoadMembers(SelectedGroupName)
    End Sub

    Private Sub DeleteRollOutToolStripMenuItem_Click(sender As Object, e As EventArgs)

    End Sub
    Private Sub CreateToolStripMenuItem_Click(sender As Object, e As EventArgs) Handles CreateToolStripMenuItem.Click
        Dim CreateRollOutForm As New CreateRollout
        CreateRollOutForm.MainForm = Me
        If CreateRollOutForm.ShowDialog() = DialogResult.OK Then
            WriteLogs(CreateRollOutForm.txtsubject.Text & " Created")
        End If
    End Sub

    Private Sub SendToolStripMenuItem_Click(sender As Object, e As EventArgs) Handles SendToolStripMenuItem.Click
        DataGridMembers.Refresh()

        Dim SendRollOutDialog As New ChooseRollout
        SendRollOutDialog.SelectedGroupPath = SelectedGroupPath
        If SendRollOutDialog.ShowDialog() = DialogResult.OK Then
            Freeze()

            SelectecRollOutName = SendRollOutDialog.ListBox1.SelectedItem.ToString
            WriteLogs("Sending " & SelectecRollOutName & " to " & SelectedGroupPath)
            Dim SendThread As New Threading.Thread(AddressOf SendRollOut)
            SendThread.Start()
            ThreadList.Add(SendThread)
        End If
    End Sub

    Private Sub DeleteToolStripMenuItem1_Click(sender As Object, e As EventArgs) Handles DeleteToolStripMenuItem1.Click
        DataGridMembers.Refresh()


        Dim SendRollOutDialog As New ChooseRollout
        SendRollOutDialog.SelectedGroupPath = SelectedGroupPath
        If SendRollOutDialog.ShowDialog() = DialogResult.OK Then
            SelectecRollOutName = SendRollOutDialog.ListBox1.SelectedItem.ToString
            If MsgBox("Are you sure you want to delete " & "", vbYesNo) = MsgBoxResult.Yes Then
                If MsgBox("Also data from store?", vbYesNo) = MsgBoxResult.Yes Then
                    WriteLogs("Deleting.. " & SelectecRollOutName & " to " & SelectedGroupPath)
                    Freeze()
                    Dim Thread As New Threading.Thread(AddressOf DeleteRollOut)
                    Thread.Start()
                    ThreadList.Add(Thread)
                Else
                    Try
                        Dim SelectedRollOutFile As New FileInfo(SelectedGroupPath & SelectecRollOutName)
                        File.Delete(SelectedRollOutFile.FullName)
                        MsgBox("Deleted")
                    Catch ex As Exception
                    End Try
                End If
            End If
        End If
    End Sub

    Private Sub AddToolStripMenuItem_Click(sender As Object, e As EventArgs) Handles AddToolStripMenuItem.Click
        Dim GroupMaintenanceForm As New AddGroup
        GroupMaintenanceForm.Method = "Add"
        If GroupMaintenanceForm.ShowDialog() = DialogResult.OK Then
            If AddGroup(GroupMaintenanceForm.txtGroupName.Text, GroupMaintenanceForm.txtGroupPath.Text) = True Then
                MsgBox("Group Added!", vbInformation)
                LoadGroups()
            End If
        End If
    End Sub

    Private Sub EditToolStripMenuItem_Click(sender As Object, e As EventArgs) Handles EditToolStripMenuItem.Click
        Try
            For Each selecteditems As DataGridViewRow In DataGridGroup.SelectedRows
                'GroupIdValue = selecteditems.Cells(0).Value
                SelectedGroupName = selecteditems.Cells("GroupName").Value
                SelectedGroupPath = selecteditems.Cells("GroupPath").Value
                Exit For
            Next
            If SelectedGroupName <> "" Or SelectedGroupName <> Nothing Then
                Dim GroupMaintenanceForm As New AddGroup
                GroupMaintenanceForm.Method = "Edit"
                GroupMaintenanceForm.txtGroupName.Text = SelectedGroupName
                GroupMaintenanceForm.txtGroupPath.Text = SelectedGroupPath
                If GroupMaintenanceForm.ShowDialog() = DialogResult.OK Then
                    Dim OldGroupName As String = SelectedGroupName
                    Dim OldGRoupPath As String = SelectedGroupPath
                    Dim NewGroupName As String = GroupMaintenanceForm.txtGroupName.Text
                    Dim NewGroupPath As String = GroupMaintenanceForm.txtGroupPath.Text
                    If EditGroup(OldGroupName, NewGroupName, OldGRoupPath, NewGroupPath) Then
                        MsgBox("Update Success!", vbInformation)
                        LoadGroups()
                    End If
                End If
            End If
        Catch ex As Exception
            MsgBox(ex.Message)
        End Try

    End Sub

    Private Sub DeleteToolStripMenuItem2_Click(sender As Object, e As EventArgs) Handles DeleteToolStripMenuItem2.Click
        Dim answer As MsgBoxResult
        answer = MsgBox("Are you sure you want to delete " & SelectedGroupName & "?", MsgBoxStyle.YesNo)
        If answer = MsgBoxResult.Yes Then
            DeleteGroup(SelectedGroupName)
            LoadGroups()
        End If
    End Sub

    Private Sub AddToolStripMenuItem1_Click(sender As Object, e As EventArgs) Handles AddToolStripMenuItem1.Click
        Dim MemberMaintenanceForm As New MemberDialog
        If MemberMaintenanceForm.ShowDialog = DialogResult.OK Then
            Dim MemberName As String = MemberMaintenanceForm.txtmembername.Text
            Dim MemberSharedPath As String = MemberMaintenanceForm.txtsharedpath.Text

            If SelectedGroupName = "" Then
                MsgBox("Please select a Group", vbExclamation)
                Return
            End If

            If AddMember(SelectedGroupName, SelectedGroupPath, MemberName, MemberSharedPath, MemberMaintenanceForm.MemberID) = True Then
                MsgBox("Member Added!", vbInformation)
                LoadMembers(SelectedGroupName)
            End If
        End If
    End Sub

    Private Sub VerifyToolStripMenuItem_Click(sender As Object, e As EventArgs) Handles VerifyToolStripMenuItem.Click
        DataGridMembers.Refresh()
        Freeze()
        Dim Thread As New Threading.Thread(AddressOf VerifyInstallation)
        Thread.Start()
        ThreadList.Add(Thread)

    End Sub

    Private Sub PropertiesToolStripMenuItem_Click(sender As Object, e As EventArgs) Handles PropertiesToolStripMenuItem.Click
        If MemberName = "" Or SelectedGroupName = "" Then
            Return
        End If
        Dim storeprop As New StoreProperties
        storeprop.StoreName = MemberName
        storeprop.StorePath = MemberPath
        storeprop.ShowDialog()

    End Sub

    Private Sub UpdateToolStripMenuItem1_Click(sender As Object, e As EventArgs) Handles UpdateToolStripMenuItem1.Click
        Dim a = MsgBox("Are you sure you want to update Auto Roll Out?", vbYesNo, "Update All")
        If a = MsgBoxResult.Yes Then
            Dim OpenFile As New OpenFileDialog
            OpenFile.Multiselect = False
            OpenFile.RestoreDirectory = True
            OpenFile.Filter = "AutoRollOut Exe (*.exe)|*.exe|All files (*.*)|*.*"

            If OpenFile.ShowDialog() = DialogResult.OK Then
                Freeze()
                Dim t As New Threading.Thread(AddressOf UpdatedAllAutoRollOut)
                t.Start(OpenFile.FileName.ToString())
            End If
        End If
    End Sub




    Private Sub Button1_Click_1(sender As Object, e As EventArgs) Handles Button1.Click
        SendEmail("AutoRollout BETA Email Please Delete.", "rollout.txt", "EMPLOYEE_DISCOUNT_UPDATE.rar", "Lois Rosas", "MIS")
        'SendNotesMail("Auto Rollout Domino API", "C:\Users\sergentlois\Desktop\Excel Docs\Q1 DRINKS.xlsx", "Lois Rosas/MIS/Roasters", "Test", True)
        'MsgBox(GetStoreEmail("KR_DELAROSA"))

    End Sub


End Class
